package com.garbagecan.cachestudy.jcs;

import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;

public class SimpleExample {
	
	private static Log log = LogFactory.getLog(SimpleExample.class);
	
	private JCS cache;
	
	private String myKey = "myKey";
	private String myValue = "myValue";
	String myGroup1 = "mygroup1";
	String myGroup2 = "mygroup2";
	private int count = 10;
	
	public static void main(String[] args) throws Exception {
		SimpleExample t = new SimpleExample();
		//t.testAdd();
		//t.testRemove();
		t.testAddToGroup();
		t.testRemoveFromGroup();
	}
	
	private SimpleExample() {
		try {
			cache = JCS.getInstance("myCache");
		} catch (CacheException e) {
			e.printStackTrace();
		}
	}
	
	private void testAdd() {
		log.info("--------------- testAdd ---------------");
		try {
			for( int i = 0 ; i < count ; i++) {
				cache.put(myKey + i, myValue + i);
			}
			for( int i = 0 ; i < count ; i++) {
				log.info(cache.get(myKey + i));
			}
		} catch (CacheException e) {
			e.printStackTrace();
		}
	}
	
	private void testRemove() {
		log.info("--------------- testRemove ---------------");
		try {
			for( int i = 0 ; i < count ; i++) {
				cache.remove(myKey + i);
			}
			for( int i = 0 ; i < count ; i++) {
				log.info(cache.get(myKey + i));
			}
		} catch (CacheException e) {
			e.printStackTrace();
		}
	}
	
	private void testAddToGroup() {
		log.info("--------------- testAddGroup ---------------");
		try {
			for( int i = 0 ; i < count ; i++) {
				cache.putInGroup(myKey + i, myGroup1, myValue + i);
				cache.putInGroup(myKey + i, myGroup2, myValue + i);
			}
			for( int i = 0 ; i < count ; i++) {
				log.info(cache.getFromGroup(myKey + i, myGroup1));
				log.info(cache.getFromGroup(myKey + i, myGroup2));
			}
		} catch (CacheException e) {
			e.printStackTrace();
		}
	}
	
	private void testRemoveFromGroup() {
		log.info("--------------- testRemoveFromGroup ---------------");
		
		Set keys1 = cache.getGroupKeys(myGroup1);
		Set keys2 = cache.getGroupKeys(myGroup2);
		
		log.info(cache.getGroupKeys(myGroup1).size());
		log.info(cache.getGroupKeys(myGroup2).size());
		
		for(Object key : keys1) {
			cache.remove(key, myGroup1);
			log.info(cache.getFromGroup(key, myGroup1));
		}
		for(Object key : keys2) {
			cache.remove(key, myGroup2);
			log.info(cache.getFromGroup(key, myGroup2));
		}
		log.info(cache.getGroupKeys(myGroup1).size());
		log.info(cache.getGroupKeys(myGroup2).size());
	}
}
